/*******************************************************************************
 * Copyright (c) 2013 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
/**
 * 
 */
package com.niannian.activity;

import java.io.File;
import java.util.Calendar;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.niannian.activity.FamilyMemberEditActivity.updateUserinfo;
import com.niannian.adapter.NumericWheelAdapter;
import com.niannian.adapter.OnWheelScrollListener;
import com.niannian.dialog.GenderDialog;
import com.niannian.dialog.SelectPhotoDialog;
import com.niannian.dialog.GenderDialog.onSimpleOnManListener;
import com.niannian.dialog.GenderDialog.onSimpleOnWomanListener;
import com.niannian.util.AsyncHandle;
import com.niannian.util.BitmapUtil;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.Sys;
import com.niannian.util.VAR;
import com.niannian.view.CircleImageView;
import com.niannian.view.WheelView;
import com.niannian.web.nnSyncApi;
import com.niannian.BaseActivity;
import com.niannian.MyApplication;
import com.niannian.R;

/**
 * 编辑个人休息
 * 
 * @author shengl
 * 
 */
public class MyInfoEditActivity extends BaseActivity {
	CircleImageView reg_my_edit_head_img;
	TextView tv_my_edit_nickname, tv_my_edit_birth, tv_my_edit_gender, tv_my_phone;
	LinearLayout ll_my_edit_head_img, ll_my_edit_nickname, ll_my_edit_gender, ll_my_edit_birth, ll_my_phone;

	private View brithdayView;
	private PopupWindow popup;
	private final int year_start = 1920;

	String nickname = "", gender = "U", avatar = "", birth = "";
	private File phoneSavePath = null;
	int currentUpdataType = -1;
	private long mExitTime;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_info_edit);
		initView();
		setLister();
		initTopView();

		initDta();
		updateView();
	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right;
	private TextView top_title;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.VISIBLE);
		iv_top_left2.setVisibility(View.GONE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.VISIBLE);
		top_title2.setVisibility(View.GONE);
		top_title.setText("编辑");

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setVisibility(View.GONE);

		iv_top_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myfinish();
			}
		});

	}

	private void initView() {

		reg_my_edit_head_img = (CircleImageView) findViewById(R.id.reg_my_edit_head_img);
		tv_my_edit_nickname = (TextView) findViewById(R.id.tv_my_edit_nickname);
		tv_my_edit_birth = (TextView) findViewById(R.id.tv_my_edit_birth);
		tv_my_edit_gender = (TextView) findViewById(R.id.tv_my_edit_gender);
		tv_my_phone = (TextView) findViewById(R.id.tv_my_phone);

		ll_my_edit_head_img = (LinearLayout) findViewById(R.id.ll_my_edit_head_img);
		ll_my_edit_nickname = (LinearLayout) findViewById(R.id.ll_my_edit_nickname);
		ll_my_edit_gender = (LinearLayout) findViewById(R.id.ll_my_edit_gender);
		ll_my_edit_birth = (LinearLayout) findViewById(R.id.ll_my_edit_birth);
		ll_my_phone = (LinearLayout) findViewById(R.id.ll_my_phone);

	}

	private void setLister() {

		reg_my_edit_head_img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (System.currentTimeMillis() - mExitTime > INTERVAL) {
					Intent intent = new Intent(MyInfoEditActivity.this, OriginalImage.class);
					intent.putExtra("display", Common.getAvatarThumbs(userInfoManager.avatar));
					intent.putExtra("OriginalImageUrl", Common.getAvatarOriginals(userInfoManager.avatar));
					MyInfoEditActivity.this.startActivity(intent);
					mExitTime = System.currentTimeMillis();
				}
			}
		});

		ll_my_edit_head_img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				phoneSavePath = new File(MyApplication.FILE_PATH_IMAGES_BIG + userInfoManager.id + "headtemp.jpg");
				SelectPhotoDialog dialog = new SelectPhotoDialog(MyInfoEditActivity.this, R.style.MyDialogStyle, phoneSavePath);
				dialog.show();

			}
		});
		ll_my_edit_nickname.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				Bundle pBundle = new Bundle();
				pBundle.putInt("type", VAR.EDIT_NICKNAME);
				pBundle.putString("currentData", nickname);
				openActivity(EditInfoActivity.class, pBundle, VAR.EDIT_NICKNAME);
			}
		});

		ll_my_edit_gender.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				genserDialog();
			}
		});
		ll_my_edit_birth.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				brithdayView = LayoutInflater.from(MyInfoEditActivity.this).inflate(R.layout.year_month_day, null);
				TextView title = (TextView) brithdayView.findViewById(R.id.wheel_title);
				final WheelView year = (WheelView) brithdayView.findViewById(R.id.wheel_year);
				final WheelView month = (WheelView) brithdayView.findViewById(R.id.wheel_month);
				final WheelView day = (WheelView) brithdayView.findViewById(R.id.wheel_day);

				title.setText("选择生日");
				String tm = tv_my_edit_birth.getText().toString();

				if (Common.empty(tm)) {
					tm = "1990-1-1";
				}

				Calendar old = Sys.StringToDate(tm, "yyyy-MM-dd");
				int tmp_year = old.get(Calendar.YEAR);
				int tmp_month = old.get(Calendar.MONTH) + 1;
				int tmp_day = old.get(Calendar.DAY_OF_MONTH);

				Calendar c = Calendar.getInstance();

				year.setAdapter(new NumericWheelAdapter(year_start, c.get(Calendar.YEAR), "%02d", "年"));

				year.setCyclic(true);
				year.setCurrentItem(tmp_year - year_start);

				month.setAdapter(new NumericWheelAdapter(1, 12, "%02d", "月"));
				month.setCyclic(true);
				month.setCurrentItem(tmp_month - 1);

				day.setAdapter(new NumericWheelAdapter(1, c.getActualMaximum(Calendar.DAY_OF_MONTH), "%02d", "日"));
				day.setCyclic(true);
				day.setCurrentItem(tmp_day - 1);

				year.addScrollingListener(new OnWheelScrollListener() {

					@Override
					public void onScrollingStarted(WheelView wheel) {
					}

					@Override
					public void onScrollingFinished(WheelView wheel) {
						Calendar tmp = Calendar.getInstance();
						int _year_index = year.getCurrentItem();
						int _month_index = month.getCurrentItem();
						tmp.set(Calendar.YEAR, _year_index + year_start);
						tmp.set(Calendar.MONTH, _month_index);
						int _max_day_of_month = tmp.getActualMaximum(Calendar.DAY_OF_MONTH);
						day.setAdapter(new NumericWheelAdapter(1, _max_day_of_month, "%02d", "日"));

						if (day.getCurrentItem() > _max_day_of_month - 1) {
							day.setCurrentItem(0);
						}
					}
				});

				month.addScrollingListener(new OnWheelScrollListener() {

					@Override
					public void onScrollingStarted(WheelView wheel) {
					}

					@Override
					public void onScrollingFinished(WheelView wheel) {
						Calendar tmp = Calendar.getInstance();
						int _year_index = year.getCurrentItem();
						int _month_index = month.getCurrentItem();
						tmp.set(Calendar.YEAR, _year_index + year_start);
						tmp.set(Calendar.MONTH, _month_index);
						int _max_day_of_month = tmp.getActualMaximum(Calendar.DAY_OF_MONTH);
						day.setAdapter(new NumericWheelAdapter(1, _max_day_of_month, "%02d", "日"));

						if (day.getCurrentItem() > _max_day_of_month - 1) {
							day.setCurrentItem(0);
						}
					}
				});

				Button btn_ok = (Button) brithdayView.findViewById(R.id.btn_ok);
				btn_ok.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						int nYear = year.getCurrentItem() + year_start;
						int nMonth = month.getCurrentItem() + 1;
						int nDay = day.getCurrentItem() + 1;
						tv_my_edit_birth.setText(String.format("%02d-%02d-%02d", nYear, nMonth, nDay));
						popup.dismiss();
						birth = tv_my_edit_birth.getText().toString().trim();
						currentUpdataType = VAR.EDIT_BIRTH;
						updateView();
						new updateUserinfo().init(null).execute();
					}
				});

				Button btn_cancel = (Button) brithdayView.findViewById(R.id.btn_cancel);
				btn_cancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						popup.dismiss();
					}
				});

				popup = new PopupWindow(brithdayView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				popup.setBackgroundDrawable(new BitmapDrawable());
				popup.setAnimationStyle(R.style.ModePopupAnimation);
				popup.setOutsideTouchable(true);
				popup.setFocusable(true);

				popup.showAtLocation(ll_my_edit_birth, Gravity.CENTER, 0, 0);

			}
		});
		ll_my_phone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				openActivity(BindingPhoneActivity.class);
				startAnimationLeftToRight();
			}
		});
	}

	private void initDta() {
		nickname = userInfoManager.nickname;
		gender = userInfoManager.gender;
		avatar = userInfoManager.avatar;
		birth = userInfoManager.birth;
		myApplication.finalbitmap.display(reg_my_edit_head_img, Common.getAvatarThumbs(avatar));
	}

	private void updateView() {
		tv_my_edit_nickname.setText(nickname);

		if ("M".equals(gender)) {
			tv_my_edit_gender.setText("男");
		} else if ("F".equals(gender)) {
			tv_my_edit_gender.setText("女");
		} else {
			tv_my_edit_gender.setText("");
		}
		tv_my_edit_birth.setText(birth);
		if (userInfoManager.phone.length() > 0) {
			tv_my_phone.setText(userInfoManager.phone);
			ll_my_phone.setEnabled(false);
		} else {
			ll_my_phone.setEnabled(true);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (RESULT_OK != resultCode) {
			return;
		}
		switch (requestCode) {
		case VAR.PHOTO_HRAPH:
			try {
				imageCrop(phoneSavePath.getAbsolutePath());
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;

		case VAR.PHOTO_ALBUM:
			try {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				if (cursor != null) {
					int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					if (cursor.getCount() > 0 && cursor.moveToFirst()) {
						String path = cursor.getString(column_index);
						imageCrop(path);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case VAR.PHOTO_OK:
			String imagePath = data.getStringExtra("path");
			Log.i(VAR.LEVEL_INFO, imagePath);
			if (!Common.empty(imagePath)) {
				try {
					Bitmap headimage = BitmapUtil.getSmallBitmap(imagePath);
					reg_my_edit_head_img.setImageBitmap(headimage);
					avatar = MyApplication.FILE_PATH_TEMP + userInfoManager.id + "headtemp.jpg";
					File file = new File(avatar);
					if (file.exists()) {
						file.delete();
					}
					BitmapUtil.saveBmp(headimage, avatar, 50);
					file = new File(avatar);
					if (!file.exists()) {
						Common.tip(MyInfoEditActivity.this, "图片保存失败");
					} else {
						currentUpdataType = VAR.EDIT_AVATAR;
						new updateUserinfo().init(MyInfoEditActivity.this, null, true, "上传中...").execute();

					}
				} catch (Exception e) {
					Common.tip(MyInfoEditActivity.this, "图片保存失败");
				}
			}
			break;
		case VAR.EDIT_NICKNAME:
			nickname = data.getStringExtra("rdata");
			currentUpdataType = VAR.EDIT_NICKNAME;
			new updateUserinfo().init(null).execute();
			updateView();
			break;

		case VAR.EDIT_BIRTH:
			birth = data.getStringExtra("rdata");
			currentUpdataType = VAR.EDIT_BIRTH;
			new updateUserinfo().init(null).execute();
			updateView();
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void imageCrop(String headpath) {
		Intent i = new Intent(MyInfoEditActivity.this, ImageFilterCropActivity.class);
		i.putExtra("path", headpath);
		startActivityForResult(i, VAR.PHOTO_OK);
	}

	private void genserDialog() {
		GenderDialog tip = new GenderDialog(MyInfoEditActivity.this, gender);
		tip.setOnManListener(new onSimpleOnManListener() {

			@Override
			public void onMan() {
				gender = "M";
				currentUpdataType = VAR.EDIT_GENDER;
				new updateUserinfo().init(null).execute();
				updateView();
			}
		});
		tip.setOnWoManlListener(new onSimpleOnWomanListener() {

			@Override
			public void onWoman() {
				gender = "F";
				currentUpdataType = VAR.EDIT_GENDER;
				new updateUserinfo().init(null).execute();
				updateView();
			}
		});
		tip.show();
	}

	protected class updateUserinfo extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			// Common.tip(MyInfoEditActivity.this, "修改失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {
				try {
					JSONObject userJson = paramJSONObject.getJSONObject("data");
					userInfoManager.Json2DBUser(userJson);
					update_gUser();
					return;

				} catch (Exception e) {
					// TODO: handle exception
				}
			} else {
				// Common.tip(MyInfoEditActivity.this,
				// ErrorCode.GetErrorMsg(retCode));
			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			switch (currentUpdataType) {
			case VAR.EDIT_AVATAR:
				return nnSyncApi.updateUserinfo(null, null, null, null, null, avatar, null);
			case VAR.EDIT_NICKNAME:
				return nnSyncApi.updateUserinfo(nickname, null, null, null, null, null, null);
			case VAR.EDIT_BIRTH:
				return nnSyncApi.updateUserinfo(null, null, null, null, null, null, birth);
			case VAR.EDIT_GENDER:
				return nnSyncApi.updateUserinfo(null, null, null, null, gender, null, null);
			default:
				return "";
			}
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		if (userInfoManager.phone.length() > 0) {
			tv_my_phone.setText(userInfoManager.phone);
			ll_my_phone.setEnabled(false);
		} else {
			ll_my_phone.setEnabled(true);
		}

	}
}
